<!--
 * @description  :
 * @descriptionDetail:
 * @copyright    : 浙江烟草
 * @author       : mhb
 * @create       : 2023-01-17 11:06:06
-->
/**
 * @description  : 树形结构
 * @descriptionDetail : 树形结构  数据结构{"pid":"0",id:"1",name:"",ext:{}}
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-12-05 16:22:21
 */
<template>
  <view class="page">
    <theme-navbar :isWhite="true" backText="返回" :title="title">
      <view class="nav-right-icon" @click="onConfirm()">
        确定
      </view>
    </theme-navbar>

    <view class="content">
      <view class="select-content">
        <u-input :customStyle="customStyle" :disabled="true" :border="true" placeholder="" type="textarea" :autoHeight="true" class="view" v-model="selectVal"></u-input>
      </view>

      <mescroll-body
        :top="150"
        :down="downOption"
        :up="upOption"
        :ref="mescroll"
        @init="mescrollInit"
      >
        <view class="tree_item" v-for="it in listDatas" :key="it.id">
          <view class="u-flex u-row-between u-padding-30" @click="click(it)">
            <view :style="{paddingLeft: it.level * 10 + 'rpx'}">
              {{ it.name }}
            </view>
            <view>
              <u-icon :name="rightIcon(it)" size="32"></u-icon>
            </view>
          </view>
          <u-divider height="2" :bgColor="$theme.u_border_color"></u-divider>
        </view>
      </mescroll-body>
    </view>
  </view>
</template>

<script>
import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";
import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";

/**
 * avatar 树形结构
 * @description 如下请求参数必须在打开页面的时候带上
 * @property {String} title 页面header  name
 * @property {String} requestCode 用于回执数据的时候同一页面不同请求区分
 * @property {Array}  data 元数据  平级list 数据
 * @property {String} root 根节点
 * @property {Array}  keys [0] = 元数据对应pid的key, [1] = 元数据对应id的key, [2] = 元数据对应name的key
 * @example
 * 打开页面的方法
 * this.$u.route({
 *   title: "部门选择",
 *   requestCode: "1001",
 *   root: "0",
 *   keys:JSON.stringify(["pid","id","orgName"]),
 *   data:JSON.stringify([{},{},{},{}]) , //平级数据
 * });
 * 回执：
 * 在调用上面打开方法的Page页的 onShow 方法中写如下代码：
 *
 * uni.$on("stCallback", res => {
 *     if(res.requestCode == 之前传入的requestCode){
 *        console.log(res.data);
 *     }
 *     uni.$off('stCallback');
 * })
 *
 *
 */
export default{

  onLoad(option) {
    this.title = option.title;
    this.requestCode = option.requestCode;
    this.init(JSON.parse(option.data), option.root, JSON.parse(option.keys));
  },
  mixins:[MescrollMixin,MescrollMoreItemMixin,MescrollMoreMixin,],
  data() {
    return {
      title:"选择",
      downOption:{
        use: false,
      },
      upOption:{
        use:false,
      },
      currentPid:"0", // 当前父级  默认 0
      orgialData:[

      ], // 原始数据  平级
      selectLic:[],
      customStyle:{
        fontSize:"21",
      },
      requestCode:"",
    }
  },
  computed: {
    listDatas() {
      let self = this;
      return this.orgialData.filter(function(obj){
        return obj.isShow;
      });
    },
    selectVal(){
      let arr = [];
      for (let i = this.selectLic.length - 1 ; i >= 0; i--) {
        arr.push(this.selectLic[i].name);
      }
      return arr.join("-");
    },
  },
  methods: {
    onConfirm() {
      this.$u.route({
        type:"back",
      });
      if(this.$u.test.isEmpty(this.selectLic)){
        uni.$emit("stCallback",{
          requestCode: this.requestCode,
          data: [],
        });
      }else{
        uni.$emit("stCallback",{
          requestCode: this.requestCode,
          data: this.selectLic.reverse(),
        });
      }
    },
    init(arr, root, keys){
      this.orgialData.splice(0,this.orgialData.length);
      let level = 0;
      if(!this.$u.test.isEmpty(arr)){
        for (let i = 0; i < arr.length; i++) {
          let tmp = arr[i];
          if(root == tmp[keys[0]]){
            this.orgialData.push({
              pid:tmp[keys[0]],
              id:tmp[keys[1]],
              name:tmp[keys[2]],
              level:0,
              collapse:true,
              isShow:true,
              ext:arr[i],
            });
            this.addChild(arr,tmp[keys[1]], keys, 1);
          }
        }
      }
    },
    addChild(arr, id, keys, level){
      for (let i = 0; i < arr.length; i++) {
        let tmp = arr[i];
        if(id == tmp[keys[0]]){
          this.orgialData.push({
            pid:tmp[keys[0]],
            id:tmp[keys[1]],
            name:tmp[keys[2]],
            level:level,
            collapse:true,
            isShow:false,
            ext:arr[i],
          });
          this.addChild(arr,tmp[keys[1]], keys, (level + 1));
        }
      }
    },
    isLeaf(id){
      for (let i = 0; i < this.orgialData.length; i++) {
        if(this.orgialData[i].pid == id){
          return false;
        }
      }
      return true;
    },
    rightIcon(obj){
      if(this.isLeaf(obj.id)){
        return "arrow-right";
      }
      if(obj.collapse){
        return "arrow-down";
      }
      return "arrow-up";
    },
    getChilds(id){
      let arr = this.orgialData.filter(function(obj){
        return obj.pid == id;
      });
      if(this.$u.test.isEmpty(arr)){
        return undefined;
      }
      return arr;
    },
    click(obj){
      let index = this.getIndexByObj(obj.id);
      if(this.isLeaf(this.orgialData[index].id)){ // 如果是叶子 则直接选中
        this.selectLic = [];
        this.updateSelectLic(this.orgialData[index].id);
      }else{
        if(!this.orgialData[index].collapse){ // 已经展开的则需要收起
          this.collapse(obj.id, index);
        }else{ // 未展开的展开child
          this.orgialData[index].collapse = false;
          this.expansion(obj.id);
        }
      }
    },
    expansion(id){
      for (let i = 0; i < this.orgialData.length; i++) {
        if(this.orgialData[i].pid == id){
          this.orgialData[i].isShow = true;
        }
      }
    },
    collapse(pid,index){
      this.orgialData[index].collapse = true;
      for (let i = 0; i < this.orgialData.length; i++) {
        if(pid == this.orgialData[i].pid){
          this.orgialData[i].isShow = false;
          this.collapse(this.orgialData[i].id, i);
        }
      }
    },
    getIndexByObj(id){
      for (let i = 0; i < this.orgialData.length; i++) {
        if(this.orgialData[i].id == id){
          return i;
        }
      }
      return -1;
    },
    updateSelectLic(id){
      if(id == '0') return; // 已经是根节点
      let index = this.getIndexByObj(id);
      if(index == -1) return;
      let ob = this.orgialData[index];
      this.selectLic.push(ob);
      this.updateSelectLic(ob.pid);
    },
  },
}

</script>

<style lang="scss" scoped>
	uni-page-body{
			height: 100%;
		}
		.select-content{
			width: 100%;
			position: fixed;
			z-index: 89;
			height: 150rpx;
			background-color: white;
			.view{
				background:$u-light-color;
				margin: 5px 20px;
				padding: 5rpx 10px;
			}
		}

	.page{
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		.nav-right-icon{
			margin-right: 30rpx;
			color: $u-type-primary;
			font-size: .8rem;
		}
		.content {
			//height: 200vh;
			height: calc(100% - 44px);
			height: calc(100% - 44px - constant(safe-area-inset-top));
			height: calc(100% - 44px - env(safe-area-inset-top));
			padding: 20rpx 5rpx;
		}
		.content-bg{
			background-color: $u-bg-color;
		}
		.slot-wrap {
			display: flex;
			align-items: center;
		}
		.navbar-right {
			margin-right: 24rpx;
			display: flex;
		}

		.right-item {
			margin: 0 12rpx;
			position: relative;
			color: $u-main-color;
			display: flex;
		}
		.ifn-content{
			padding: 0rpx 5rpx 0rpx !important;
		}

	}

	.tree_item{

	}
</style>
